/*
 * @Author: Await
 * @Date: 2025-04-23 15:30:30
 * @LastEditors: Await
 * @LastEditTime: 2025-04-23 15:30:30
 * @Description: 视觉映射配置组件
 */
import React, { useState } from 'react';
import {
    Form,
    Input,
    Switch,
    Select,
    InputNumber,
    Row,
    Col,
    Typography,
    Tooltip,
    ColorPicker,
    Button,
    Divider,
    Slider,
    Space,
    Card
} from 'antd';
import { InfoCircleOutlined, PlusOutlined, MinusOutlined } from '@ant-design/icons';

// 视觉映射配置类型
export interface VisualMapConfig {
    show?: boolean;
    type?: 'continuous' | 'piecewise';
    min?: number;
    max?: number;
    calculable?: boolean;
    precision?: number;
    orient?: 'horizontal' | 'vertical';
    itemWidth?: number;
    itemHeight?: number;
    align?: 'auto' | 'left' | 'right' | 'top' | 'bottom';
    text?: string[];
    textStyle?: {
        color?: string;
        fontSize?: number;
    };
    inRange?: {
        color?: string[];
        symbolSize?: number[];
        colorAlpha?: number[];
        opacity?: number[];
    };
    outOfRange?: {
        color?: string[];
        symbolSize?: number[];
        colorAlpha?: number[];
        opacity?: number[];
    };
    categories?: string[];
    pieces?: {
        min?: number;
        max?: number;
        value?: number;
        label?: string;
        color?: string;
    }[];
    dimension?: number;
    seriesIndex?: number | number[];
    hoverLink?: boolean;
    position?: 'left' | 'right' | 'top' | 'bottom';
    left?: string | number;
    top?: string | number;
    right?: string | number;
    bottom?: string | number;
    padding?: number | number[];
}

interface VisualMapConfigProps {
    config?: VisualMapConfig;
    onChange: (config: VisualMapConfig) => void;
}

/**
 * 视觉映射配置组件
 */
const VisualMapConfig: React.FC<VisualMapConfigProps> = ({ config = {}, onChange }) => {
    // 默认视觉映射配置
    const defaultConfig: VisualMapConfig = {
        show: true,
        type: 'continuous',
        min: 0,
        max: 100,
        calculable: true,
        orient: 'vertical',
        inRange: {
            color: ['#50a3ba', '#eac736', '#d94e5d']
        },
        position: 'right'
    };

    // 确保配置对象存在
    const visualMapConfig: VisualMapConfig = { ...defaultConfig, ...config };

    // 处理配置更改
    const handleConfigChange = (key: string, value: any) => {
        // 处理嵌套属性
        if (key.includes('.')) {
            const keys = key.split('.');
            let current = { ...visualMapConfig } as any;
            
            for (let i = 0; i < keys.length - 1; i++) {
                if (!current[keys[i]]) {
                    current[keys[i]] = {};
                }
                current = current[keys[i]];
            }
            
            current[keys[keys.length - 1]] = value;
            onChange({ ...visualMapConfig });
        } else {
            onChange({ ...visualMapConfig, [key]: value });
        }
    };

    // 添加颜色配置
    const handleAddColor = () => {
        const inRangeColors = visualMapConfig.inRange?.color || [];
        handleConfigChange('inRange.color', [...inRangeColors, '#5470c6']);
    };

    // 删除颜色配置
    const handleRemoveColor = (index: number) => {
        const inRangeColors = [...(visualMapConfig.inRange?.color || [])];
        inRangeColors.splice(index, 1);
        handleConfigChange('inRange.color', inRangeColors);
    };

    // 更新颜色配置
    const handleColorChange = (color: any, index: number) => {
        const inRangeColors = [...(visualMapConfig.inRange?.color || [])];
        inRangeColors[index] = color.toHexString();
        handleConfigChange('inRange.color', inRangeColors);
    };

    // 添加分段
    const handleAddPiece = () => {
        const pieces = visualMapConfig.pieces || [];
        const newPiece = {
            min: pieces.length > 0 ? (pieces[pieces.length - 1].max || 0) : 0,
            max: pieces.length > 0 ? (pieces[pieces.length - 1].max || 0) + 20 : 20,
            label: `${pieces.length + 1}`,
            color: '#5470c6'
        };
        handleConfigChange('pieces', [...pieces, newPiece]);
    };

    // 删除分段
    const handleRemovePiece = (index: number) => {
        const pieces = [...(visualMapConfig.pieces || [])];
        pieces.splice(index, 1);
        handleConfigChange('pieces', pieces);
    };

    // 更新分段配置
    const handlePieceChange = (index: number, key: string, value: any) => {
        const pieces = [...(visualMapConfig.pieces || [])];
        pieces[index] = { ...pieces[index], [key]: value };
        handleConfigChange('pieces', pieces);
    };

    // 表单项标题组件
    const FormItemLabel = ({ children, tooltip }: { children: React.ReactNode, tooltip?: string }) => (
        <div style={{ marginBottom: 4, display: 'flex', alignItems: 'center' }}>
            <Typography.Text type="secondary" style={{ fontSize: 12 }}>
                {children}
            </Typography.Text>
            {tooltip && (
                <Tooltip title={tooltip}>
                    <InfoCircleOutlined style={{ marginLeft: 4, fontSize: 12, color: '#999' }} />
                </Tooltip>
            )}
        </div>
    );

    return (
        <Card
            title={
                <div style={{ display: 'flex', alignItems: 'center' }}>
                    <Typography.Text strong>视觉映射配置</Typography.Text>
                    <Tooltip title="将数据值映射到图形的视觉属性（如颜色、大小等），用于表现数据的大小关系">
                        <InfoCircleOutlined style={{ marginLeft: 8, fontSize: 14 }} />
                    </Tooltip>
                </div>
            }
            style={{ marginBottom: 16 }}
        >
            <div className="form-container">
                <Row gutter={[16, 8]}>
                    <Col span={12}>
                        <FormItemLabel tooltip="是否显示视觉映射控件">
                            显示控件
                        </FormItemLabel>
                        <Switch
                            checked={visualMapConfig.show !== false}
                            onChange={checked => handleConfigChange('show', checked)}
                        />
                    </Col>
                    <Col span={12}>
                        <FormItemLabel tooltip="视觉映射类型">
                            类型
                        </FormItemLabel>
                        <Select
                            value={visualMapConfig.type || 'continuous'}
                            onChange={value => handleConfigChange('type', value)}
                            style={{ width: '100%' }}
                            options={[
                                { label: '连续型', value: 'continuous' },
                                { label: '分段型', value: 'piecewise' }
                            ]}
                        />
                    </Col>
                    <Col span={12}>
                        <FormItemLabel tooltip="视觉映射的最小值，对应数据的下限">
                            最小值
                        </FormItemLabel>
                        <InputNumber
                            value={visualMapConfig.min}
                            onChange={value => handleConfigChange('min', value)}
                            style={{ width: '100%' }}
                        />
                    </Col>
                    <Col span={12}>
                        <FormItemLabel tooltip="视觉映射的最大值，对应数据的上限">
                            最大值
                        </FormItemLabel>
                        <InputNumber
                            value={visualMapConfig.max}
                            onChange={value => handleConfigChange('max', value)}
                            style={{ width: '100%' }}
                        />
                    </Col>
                    
                    <Col span={12}>
                        <FormItemLabel tooltip="是否显示拖拽手柄，可以通过拖拽调整选定范围">
                            显示拖拽手柄
                        </FormItemLabel>
                        <Switch
                            checked={visualMapConfig.calculable !== false}
                            onChange={checked => handleConfigChange('calculable', checked)}
                        />
                    </Col>
                    <Col span={12}>
                        <FormItemLabel tooltip="数值精度，显示的小数位数">
                            数值精度
                        </FormItemLabel>
                        <InputNumber
                            value={visualMapConfig.precision || 0}
                            onChange={value => handleConfigChange('precision', value)}
                            min={0}
                            max={5}
                            style={{ width: '100%' }}
                        />
                    </Col>
                    <Col span={12}>
                        <FormItemLabel tooltip="控件方向">
                            控件方向
                        </FormItemLabel>
                        <Select
                            value={visualMapConfig.orient || 'vertical'}
                            onChange={value => handleConfigChange('orient', value)}
                            style={{ width: '100%' }}
                            options={[
                                { label: '垂直', value: 'vertical' },
                                { label: '水平', value: 'horizontal' }
                            ]}
                        />
                    </Col>
                    <Col span={12}>
                        <FormItemLabel tooltip="是否与图表元素联动，鼠标悬停到元素上时，视觉映射控件会高亮相应部分">
                            联动高亮
                        </FormItemLabel>
                        <Switch
                            checked={visualMapConfig.hoverLink !== false}
                            onChange={checked => handleConfigChange('hoverLink', checked)}
                        />
                    </Col>
                    <Col span={24}>
                        <Divider orientation="left">控件位置</Divider>
                    </Col>
                    <Col span={12}>
                        <FormItemLabel tooltip="控件位置">
                            位置类型
                        </FormItemLabel>
                        <Select
                            value={visualMapConfig.position || 'right'}
                            onChange={value => handleConfigChange('position', value)}
                            style={{ width: '100%' }}
                            options={[
                                { label: '左侧', value: 'left' },
                                { label: '右侧', value: 'right' },
                                { label: '顶部', value: 'top' },
                                { label: '底部', value: 'bottom' }
                            ]}
                        />
                    </Col>
                    <Col span={24}>
                        <Divider orientation="left">
                            {visualMapConfig.type === 'piecewise' ? '分段设置' : '颜色映射'}
                        </Divider>
                    </Col>
                    
                    {visualMapConfig.type === 'continuous' && (
                        <>
                            <Col span={24}>
                                <FormItemLabel tooltip="颜色映射，从小到大对应的颜色变化">
                                    颜色列表
                                    <Button
                                        type="text"
                                        icon={<PlusOutlined />}
                                        onClick={handleAddColor}
                                        size="small"
                                        style={{ marginLeft: 8 }}
                                    >
                                        添加颜色
                                    </Button>
                                </FormItemLabel>
                                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginTop: 8 }}>
                                    {(visualMapConfig.inRange?.color || []).map((color, index) => (
                                        <div key={index} style={{ display: 'flex', alignItems: 'center' }}>
                                            <ColorPicker
                                                value={color}
                                                onChange={color => handleColorChange(color, index)}
                                                size="middle"
                                                showText
                                            />
                                            <Button
                                                type="text"
                                                danger
                                                icon={<MinusOutlined />}
                                                onClick={() => handleRemoveColor(index)}
                                                disabled={(visualMapConfig.inRange?.color || []).length <= 1}
                                                size="small"
                                            />
                                        </div>
                                    ))}
                                </div>
                            </Col>
                            <Col span={24} style={{ marginTop: 16 }}>
                                <div style={{ 
                                    height: 30, 
                                    background: `linear-gradient(to right, ${(visualMapConfig.inRange?.color || []).join(', ')})`,
                                    borderRadius: 4,
                                    position: 'relative'
                                }}>
                                    <div style={{ position: 'absolute', left: 0, bottom: -20, fontSize: 12, color: '#666' }}>
                                        {visualMapConfig.min}
                                    </div>
                                    <div style={{ position: 'absolute', right: 0, bottom: -20, fontSize: 12, color: '#666' }}>
                                        {visualMapConfig.max}
                                    </div>
                                </div>
                            </Col>
                        </>
                    )}
                    
                    {visualMapConfig.type === 'piecewise' && (
                        <>
                            <Col span={24} style={{ marginBottom: 16 }}>
                                <Button
                                    type="primary"
                                    icon={<PlusOutlined />}
                                    onClick={handleAddPiece}
                                >
                                    添加分段
                                </Button>
                            </Col>
                            
                            {(visualMapConfig.pieces || []).map((piece, index) => (
                                <Col span={24} key={index}>
                                    <Card
                                        size="small"
                                        title={`分段 ${index + 1}`}
                                        extra={
                                            <Button
                                                type="text"
                                                danger
                                                icon={<MinusOutlined />}
                                                onClick={() => handleRemovePiece(index)}
                                            />
                                        }
                                        style={{ marginBottom: 8 }}
                                    >
                                        <Row gutter={[16, 8]}>
                                            <Col span={12}>
                                                <FormItemLabel tooltip="分段的最小值">
                                                    最小值
                                                </FormItemLabel>
                                                <InputNumber
                                                    value={piece.min}
                                                    onChange={value => handlePieceChange(index, 'min', value)}
                                                    style={{ width: '100%' }}
                                                />
                                            </Col>
                                            <Col span={12}>
                                                <FormItemLabel tooltip="分段的最大值">
                                                    最大值
                                                </FormItemLabel>
                                                <InputNumber
                                                    value={piece.max}
                                                    onChange={value => handlePieceChange(index, 'max', value)}
                                                    style={{ width: '100%' }}
                                                />
                                            </Col>
                                            <Col span={12}>
                                                <FormItemLabel tooltip="分段的标签文本">
                                                    标签
                                                </FormItemLabel>
                                                <Input
                                                    value={piece.label}
                                                    onChange={e => handlePieceChange(index, 'label', e.target.value)}
                                                    placeholder="分段标签"
                                                />
                                            </Col>
                                            <Col span={12}>
                                                <FormItemLabel tooltip="分段对应的颜色">
                                                    颜色
                                                </FormItemLabel>
                                                <ColorPicker
                                                    value={piece.color}
                                                    onChange={color => handlePieceChange(index, 'color', color.toHexString())}
                                                    showText
                                                />
                                            </Col>
                                        </Row>
                                    </Card>
                                </Col>
                            ))}
                        </>
                    )}
                    
                    <Col span={24}>
                        <Divider orientation="left">文本设置</Divider>
                    </Col>
                    <Col span={12}>
                        <FormItemLabel tooltip="上下/左右两端的文本">
                            两端文本
                        </FormItemLabel>
                        <Space.Compact style={{ width: '100%' }}>
                            <Input
                                value={(visualMapConfig.text || [])[0]}
                                onChange={e => {
                                    const text = visualMapConfig.text || [];
                                    handleConfigChange('text', [e.target.value, text[1] || '']);
                                }}
                                placeholder="最小值文本"
                                style={{ width: '50%' }}
                            />
                            <Input
                                value={(visualMapConfig.text || [])[1]}
                                onChange={e => {
                                    const text = visualMapConfig.text || [];
                                    handleConfigChange('text', [text[0] || '', e.target.value]);
                                }}
                                placeholder="最大值文本"
                                style={{ width: '50%' }}
                            />
                        </Space.Compact>
                    </Col>
                    <Col span={12}>
                        <FormItemLabel tooltip="文本样式颜色">
                            文本颜色
                        </FormItemLabel>
                        <ColorPicker
                            value={visualMapConfig.textStyle?.color || '#333'}
                            onChange={color => handleConfigChange('textStyle.color', color.toHexString())}
                            showText
                        />
                    </Col>
                    <Col span={12}>
                        <FormItemLabel tooltip="文本字体大小">
                            文本大小
                        </FormItemLabel>
                        <InputNumber
                            value={visualMapConfig.textStyle?.fontSize || 12}
                            onChange={value => handleConfigChange('textStyle.fontSize', value)}
                            min={10}
                            max={20}
                            style={{ width: '100%' }}
                        />
                    </Col>
                </Row>
            </div>
        </Card>
    );
};

export default VisualMapConfig;